package org.rency.crawler.dal.dao.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import java.util.List;
import javax.annotation.Resource;
import org.rency.crawler.dal.dao.FetchStateRuleDao;
import org.rency.crawler.dal.entity.FetchStateRuleDO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/11/21 18:49<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/21 18:49
 */
@Repository
public class FetchStateRuleDaoImpl implements FetchStateRuleDao {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override
  public FetchStateRuleDO load(String id) {
    Criteria criteria = Criteria.where("id").is(id);
    return mongoTemplate.findOne(new Query(criteria),FetchStateRuleDO.class);
  }

  @Override
  public List<FetchStateRuleDO> findAll() {
    return mongoTemplate.findAll(FetchStateRuleDO.class);
  }

  @Override
  public List<FetchStateRuleDO> find(String fsCode) {
    Criteria criteria = Criteria.where("fsCode").is(fsCode);
    return mongoTemplate.find(new Query(criteria),FetchStateRuleDO.class);
  }

  @Override
  public FetchStateRuleDO find(String fsCode, String fsStatus) {
    Criteria criteria = Criteria.where("fsCode").is(fsCode)
        .and("fsStatus").is(fsStatus);
    return mongoTemplate.findOne(new Query(criteria),FetchStateRuleDO.class);
  }

  @Override
  public boolean save(FetchStateRuleDO entity) {
    try {
      mongoTemplate.save(entity);
      return true;
    } catch (DuplicateKeyException e) {
      return true;
    }
  }

  @Override
  public boolean updateRetryTimes(String id, int retryTimes) {
    Criteria criteria = Criteria.where("id").is(id);
    Update update = Update.update("retryTimes", retryTimes);
    UpdateResult result = mongoTemplate.updateFirst(new Query(criteria),update,FetchStateRuleDO.class);
    return result.getModifiedCount() == 1;
  }

  @Override
  public boolean delete(String id) {
    DeleteResult result = mongoTemplate
        .remove(new Query(Criteria.where("id").is(id)), FetchStateRuleDO.class);
    return result.getDeletedCount() == 1;
  }
}
